package com.aispace.taichu.modules.dynamic.model.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aispace.taichu.modules.dynamic.model.mapper.ModelConfigMapper;
import com.aispace.taichu.modules.dynamic.model.model.entity.ModelConfig;
import com.aispace.taichu.modules.dynamic.model.service.IModelConfigService;
import com.aispace.taichu.modules.listener.ModelChangeEvent;
import com.aispace.taichu.modules.listener.TaiChuEventPublisher;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 大模型配置表 服务实现类
 * </p>
 *
 * @author chengjie.guo
 * @since 2025-09-25
 */
@Service
@Slf4j
@AllArgsConstructor
public class ModelConfigServiceImpl extends ServiceImpl<ModelConfigMapper, ModelConfig> implements IModelConfigService {

    private final TaiChuEventPublisher publisher;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefault(Long modelId) {
        // 参数校验
        if (modelId == null) {
            throw new IllegalArgumentException("modelId cannot be null");
        }

        // 先取消当前默认模型
        QueryWrapper<ModelConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModelConfig::getIsDefault, true);
        ModelConfig config = this.getOne(queryWrapper);
        if (config != null) {
            config.setIsDefault(false);
            this.updateById(config);
        }

        // 设置新的默认模型
        ModelConfig modelConfig = this.getById(modelId);
        if (modelConfig == null) {
            throw new IllegalArgumentException("ModelConfig not found with id: " + modelId);
        }
        modelConfig.setIsDefault(true);
        ModelChangeEvent modelChangeEvent = new ModelChangeEvent(modelConfig);
        boolean updated = this.updateById(modelConfig);
        if (!updated) {
            throw new RuntimeException("Failed to update modelConfig with id: " + modelId);
        }else {
            log.info("Set model: {} as default model", modelConfig.getModelName());
            publisher.publishChange(modelChangeEvent);
        }
        return updated;
    }

}
